package cn.zxl.spring.holiday.job.util;

import cn.zxl.spring.holiday.job.domain.Department;
import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.service.DepartmentService;
import cn.zxl.spring.holiday.job.service.EmployeeService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2021/10/7 22:46
 * @Version 1.0
 * @Description
 */
public class EmployeeDataListener extends AnalysisEventListener<Employee> {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    /**
     * 缓存的数据
     */
    private List<Employee> list = new ArrayList<>(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private EmployeeService employeeService;

    private DepartmentService departmentService;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param
     */
    public EmployeeDataListener(EmployeeService employeeService, DepartmentService departmentService) {
        this.employeeService = employeeService;
        this.departmentService = departmentService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Employee data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        Employee employee = employeeService.findByUsername(data.getUsername());
        if (employee == null) {
            List<Department> departments = departmentService.listAll();
            if (departments != null && departments.size() > 0) {
                for (Department department : departments) {
                    if (department.getName().equals(data.getDept().getName())) {
                        data.setDeptId(department.getId());
                    }
                }
            }
            data.setSlat(data.getSlat());
            Md5Hash md5 = new Md5Hash(data.getUsername(), data.getUsername(), 3);
            data.setPassword(md5.toString());
            data.setAdmin(false);
            this.list.add(data);
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        if (list != null && list.size() > 0) {
            for (Employee employee : list) {
                employeeService.save(employee);
            }
        }
        LOGGER.info("存储数据库成功！");
    }
}
